package com.apkj.nutz.modules

import instep.lang.FileUtils
import org.nutz.lang.Files
import org.nutz.log.Log
import org.nutz.log.Logs
import org.nutz.mvc.Mvcs
import org.nutz.mvc.annotation.*
import org.nutz.mvc.upload.TempFile
import org.nutz.mvc.upload.UploadAdaptor
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

import javax.servlet.http.HttpServletRequest

/**
 * Created by IPKJ on 2015/12/8.
 */
@At("/us")
@AdaptBy(type = UploadAdaptor::class)
open class FileKotilnModule {
    private var serverName: String ? = null
    private var log: Log = Logs.get()

    @At
    @Ok("raw")
    @POST
    fun upload(@Param("file") tfile: TempFile, @Param("uuid") tuuid: String): String {

        var req: HttpServletRequest = Mvcs.getReq();
        serverName = req.getContextPath()
        if (this.serverName == null) {
            this.serverName = "other"
        }
        var file: File = tfile.file
        var uuid: String = tuuid

        var savePath = System.getenv("APP_UPLOAD_HOME");

        var ym: String = SimpleDateFormat("yyyyMM").format(Date());
        var createDir: String = savePath + "\\" + serverName + "\\" + ym;
        var f: File = File(createDir);
        if (!f.exists()) {
            log.info("create Dir if not Exists...")
            FileUtils.createDirIfNoExists(f)
        };
        var fileType: String = Files.getSuffix(file);
        if (uuid == "") {
            uuid = UUID.randomUUID().toString();
        }

        var fullPath: String = createDir + "\\" + uuid + fileType;
        try {
            FileUtils.copy(file, File(fullPath));
        }
        catch (e: Exception) {
            e.printStackTrace();
        }
        return "$uuid";
    }

    @At
    @Ok("raw")
    fun download(@Param("uuid") uuid: String): String {
        log.info(uuid)
        return "ok"
    }

}